<script>
import HzSafeArea from "@/components/layout/hz/hz-safe-area.vue";
import SelectUser from "@/components/selectUser/index.vue";
import SelectAddress from "@/components/selectAddress/index.vue";
import {
  getGoodsDetail,
  addPackProductOrders,
  getPointsExchangeRatio,
  getAcceptAddressList,
  AddOrders_V2
} from '@/api/mall';
import {GetUserCoupons} from '@/api/homePage.js';

export default {
  name: "package",
  components: {
    HzSafeArea,
    SelectUser,
    SelectAddress
  },
  data() {
    const today = this.getFormattedDate(new Date());
    const tomorrow = this.getFormattedDate(this.getTomorrowDate());
    const endLimit = this.getFormattedDate(this.getDateAfterDays(15));

    return {
      today,
      tomorrow,
      endLimit,
      checked: false,
      id: '',
      packageInfo: {
        name: '',
        price: 0,
        image: '',
        businessId: '',
        productId: '',
        productSpecId: '',
        packageItems: [] // 套餐中包含的商品项目
      },
      // 通用数据
      remark: '',
      // 优惠券相关数据
      hasCoupons: false,
      useCoupons: [],
      couponTotalDiscount: 0,
      // 价格动画
      lastTotalPrice: 0,
      // 积分相关
      pointsRatio: 1, // 积分兑换比例
      isPointsPayment: false, // 是否使用积分支付
      // 提交订单防重复点击
      isSubmitting: false, // 是否正在提交订单
      // 通用游客/入住人信息
      commonGuests: []
    }
  },
  computed: {
    // 计算总价
    totalPrice() {
      let totalPrice = this.packageInfo.price;

      // 减去优惠券折扣 - 只在非积分模式下计算优惠券
      if (!this.isPointsPayment && this.couponTotalDiscount > 0) {
        totalPrice -= this.couponTotalDiscount;
        // 确保价格不低于0
        totalPrice = Math.max(0, totalPrice);
      }

      // 四舍五入保留两位小数
      totalPrice = Math.round(totalPrice * 100) / 100;

      return totalPrice;
    },

    // 计算积分总额
    totalPoints() {
      if (!this.isPointsPayment) return 0;
      return Math.round(this.totalPrice * this.pointsRatio);
    },
    currentSelectedGuests() {
      return item => item.guests;
    },
    // 判断是否需要统一的游客/入住人信息模块
    requiresCommonGuestInfo() {
      if (!this.packageInfo || !this.packageInfo.packageItems) {
        return false;
      }
      return this.packageInfo.packageItems.some(item => item.hasRzrInfo);
    },
    // 动态生成通用游客模块的标题
    commonGuestInfoTitle() {
      return '联系人信息';
    }
 },
  onLoad(options) {
    if (options) {
      this.id = options.id || '';
      // 判断是否使用积分支付
      this.isPointsPayment = options.integral === 'true' || options.integral === true;
    }
    // 设置导航栏标题
    uni.setNavigationBarTitle({title: this.$t('package.title')});

    // 如果是积分支付类型，获取积分比例
    if (this.isPointsPayment) {
      this.getPointsRatio();
    }

    // 初始化套餐信息
    this.init();

    // 获取优惠券信息 - 只在非积分模式下获取
    if (!this.isPointsPayment) {
      this.getCoupon();
    }
  },
  watch: {
    // 监听总价变化
    totalPrice(newVal, oldVal) {
      if (oldVal && newVal !== oldVal) {
        this.lastTotalPrice = parseFloat(oldVal);
      }
    }
  },
  methods: {
    changeCheked() {
      this.checked = !this.checked;
    },
    goToTermsDetail(id) {
      uni.navigateTo({
        url: `/ticket_subpages/index/article?id=${id}`
      });
    },
    // 初始化套餐数据
    async init() {
      try {
        uni.showLoading({
          title: '加载中...',
          mask: true
        });

        // 获取套餐详情
        const { Data } = await getGoodsDetail({Id: this.id});

        // 设置套餐基本信息
        this.packageInfo.name = Data.Name;
        this.packageInfo.price = Data.ShowPrice;
        this.packageInfo.image = Data.Img;
        this.packageInfo.businessId = Data.BusinessId;
        this.packageInfo.productId = Data.Id || Data.ProductId;
        this.packageInfo.productSpecId = Data.ProductSpecId;
        this.packageInfo.bookingNotice = Data.BookingNotice;
        this.packageInfo.productSpecList = Data.ProductSpecList;

        // 处理套餐中的子产品 - 使用PackProductItems
        if (Data.PackProductItems && Array.isArray(Data.PackProductItems)) {
          // 处理套餐中的每个产品项目
          this.packageInfo.packageItems = Data.PackProductItems.map((item, index) => {
            return {
              businessId: item.BusinessId,
              id: item.Id,
              name: item.Name,
              type: item.Type,
              price: item.PackPrice,
              showPrice:item.ShowPrice,
              image: item.Img,
              productId: item.Id,
              productSpecId: item.ProductSpecId,
              hasAddress: false,
              selectedAddress: null,
              hasRzDate: false,
              dateRange: [],
              hasRzrInfo: false,
              guests: [],
              hasTicket: false,
              hasTimeSlots: false,
              ticketDate: '',
              timeSlots: [],
              selectedTimeSlot: undefined,
              productSpecList: [], // 海岛玩乐用此字段
            };
          });
        }

        /**
         * 对 packageItems 里面的 项目做处理
         * 存在 type 为 2 的项目，需要展示收货地址 | 多个时给最后一项展示收货地址
         * 存在 type 为 11 的项目，需要展示使用日期、选择场次、游客
         * 存在 type 为 13 的项目，需要展示入住时间、入住人信息
         * 存在 type 为 18 的项目，需要展示使用日期、选择场次、参与人
         * 存在 type 为 19 的项目，需要展示使用日期、游客
         */
        if (this.packageInfo.packageItems.length) {
          const lastItemType2Index = this.packageInfo.packageItems.findLastIndex(item => item.type === 2);
          if (lastItemType2Index !== -1) {
            this.packageInfo.packageItems[lastItemType2Index].hasAddress = true;
            this.packageInfo.packageItems[lastItemType2Index].selectedAddress = null;
            this.getDefaultAddress(lastItemType2Index);
          }
          this.packageInfo.packageItems.forEach(item => {
            if (item.type === 13) {
              // 20250903 将套餐里面酒店日期暂时屏蔽掉
              // item.hasRzDate = true;
              item.hasRzDate = false;
              item.dateRange = [this.today, this.tomorrow];
              item.hasRzrInfo = true;
              item.guests = [];
            } else if ([11, 18].includes(item.type)) {
              item.hasTicket = true;
              item.ticketDate = this.today;
              item.hasRzrInfo = true;
              item.guests = [];
              if ([11, 18].includes(item.type)) {
                item.hasTimeSlots = true;
                this.getItemProductSpecList(item);
              }
            } else if (item.type === 19) {
              item.hasRzrInfo = true;
              item.guests = [];
              item.hasTicket = true;
              item.ticketDate = this.today;
              item.hasRzrInfo = true;
              item.guests = [];
              if ([11, 18].includes(item.type)) {
                item.hasTimeSlots = true;
                this.getItemProductSpecList(item);
              }
            } else if (item.type === 14) {
              item.hasRzrInfo = true;
              item.guests = [];
            }
          })
        }

        uni.hideLoading();
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: this.$t('package.loadFailed'),
          icon: 'none'
        });
      }
    },
    async getItemProductSpecList(item) {
      const { Data } = await getGoodsDetail({Id: item.id});
      item.productSpecList = Data.ProductSpecList;
      this.generateTimeSlots(item);
    },

    generateTimeSlots(item) {
      const { productSpecList } = item;
      if (!productSpecList || !productSpecList.length) {
        item.timeSlots = [
          {
            id: null,
            startTime: '暂无场次配置',
            endTime: '',
            available: false,
          }
        ]
        return;
      }
      // 获取当前时间
      const currentDate = new Date()
      const currentTimeInMinutes = currentDate.getHours() * 60 + currentDate.getMinutes();
      // 判断是否为当天
      const isToday = item.ticketDate === this.today;
      // 将时间字符串转换为分钟数
      const timeToMinutes = (timeStr) => {
        if (!timeStr) return 0;
        const [hours, minutes] = timeStr.split(':').map(Number);
        return hours * 60 + (minutes || 0);
      };
      // 格式化时间，从HH:MM:SS转为HH:MM
      const formatTimeString = (timeStr) => {
        if (!timeStr || timeStr === '全天可用') return timeStr;
        const parts = timeStr.split(':');
        if (parts.length >= 2) {
          return `${parts[0]}:${parts[1]}`;
        }
        return timeStr;
      };
      // 判断选择的日期是星期几 (1-7，1是周一，7是周日)
      const selectedDateObj = new Date(item.ticketDate);
      const selectedDay = selectedDateObj.getDay();
      const selectedOpenTypeDay = selectedDay === 0 ? 7 : selectedDay;
      // 1. 筛选符合用户选择日期的规则
      const validRules = [];
      for (const rule of productSpecList) {
        // 初始化规则有效性为true
        let isRuleValid = true;
        // 检查日期范围
        if (rule.StartDate) {
          const startDate = new Date(rule.StartDate);
          startDate.setHours(0, 0, 0, 0);
          if (selectedDateObj < startDate) {
            isRuleValid = false;
          }
        }
        if (isRuleValid && rule.EndDate) {
          const endDate = new Date(rule.EndDate);
          endDate.setHours(0, 0, 0, 0);
          if (selectedDateObj > endDate) {
            isRuleValid = false;
          }
        }
        // 检查星期限制
        if (isRuleValid && rule.OpenType) {
          const openDaysStr = rule.OpenType.split(',').map(d => d.trim());
          // 检查是否包含8，如果包含则表示一周7天都开放
          if (openDaysStr.includes('8')) {
            // 一周7天都开放，不需要进一步检查
          } else {
            // 常规处理，检查当前星期是否在开放列表中
            const openDays = openDaysStr.map(d => parseInt(d));
            if (!openDays.includes(selectedOpenTypeDay)) {
              isRuleValid = false;
            }
          }
        }
        // 如果规则有效，添加到符合条件的规则列表
        if (isRuleValid) {
          validRules.push(rule);
        }
      }
      // 如果没有符合条件的规则，显示无可用场次
      if (!validRules.length) {
        item.timeSlots = [{
          id: null,
          startTime: '暂无可用场次',
          endTime: '',
          available: false,
        }];
        uni.showToast({
          title: '所选日期无可用场次',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      // 2. 按Sort值从小到大排序
      validRules.sort((a, b) => {
        const sortA = typeof a.Sort === 'number' ? a.Sort : 999;
        const sortB = typeof b.Sort === 'number' ? b.Sort : 999;
        return sortA - sortB;
      });
      // 3. 选择Sort值最小的规则
      const bestRule = validRules[0];
      // 4. 处理场次数据
      let timeSlotData = [];
      if (bestRule.TicketSceneTimeList && Array.isArray(bestRule.TicketSceneTimeList) && bestRule.TicketSceneTimeList.length) {
        // 使用TicketSceneTimeList作为场次数据，并检查是否可购买
        timeSlotData = bestRule.TicketSceneTimeList.map(scene => {
          // 计算开始和结束时间(分钟)
          let startTimeInMinutes = 0;
          let endTimeInMinutes = 24 * 60 - 1; // 默认为全天
          if (scene.StartTime) startTimeInMinutes = timeToMinutes(scene.StartTime);
          if (scene.EndTime) endTimeInMinutes = timeToMinutes(scene.EndTime);
          // 判断是否可购买
          let isAvailable = true;
          if (isToday) {
            // 如果场次已经结束，不可购买
            if (currentTimeInMinutes >= endTimeInMinutes) isAvailable = false;
            // 如果距离结束不足1小时，不可购买
            else if (currentTimeInMinutes > (endTimeInMinutes - 60)) isAvailable = false;
          }
          return {
            id: scene.Id || bestRule.Id,
            startTime: formatTimeString(scene.StartTime) || '00:00',
            endTime: formatTimeString(scene.EndTime) || '23:59',
            available: isAvailable,
            sceneId: scene.Id, // 保存场次ID
            ruleName: bestRule.Name || '' // 保存规则名称
          };
        });
      } else if (bestRule.StartTime || bestRule.EndTime) {
        // 使用规则本身的StartTime和EndTime作为场次时间
        // 计算开始和结束时间(分钟)
        let startTimeInMinutes = 0;
        let endTimeInMinutes = 24 * 60 - 1; // 默认为全天
        if (bestRule.StartTime) startTimeInMinutes = timeToMinutes(bestRule.StartTime);
        if (bestRule.EndTime) endTimeInMinutes = timeToMinutes(bestRule.EndTime);
        // 判断是否可购买
        let isAvailable = true;
        if (isToday) {
          // 如果场次已经结束，不可购买
          if (currentTimeInMinutes >= endTimeInMinutes) isAvailable = false;
          // 如果距离结束不足1小时，不可购买
          else if (currentTimeInMinutes > (endTimeInMinutes - 60)) isAvailable = false;
        }
        timeSlotData = [{
          id: bestRule.Id,
          startTime: formatTimeString(bestRule.StartTime) || '00:00',
          endTime: formatTimeString(bestRule.EndTime) || '23:59',
          available: isAvailable,
          productId: bestRule.ProductId,
          productSpecId: bestRule.Id,
          ruleName: bestRule.Name || '' // 保存规则名称
        }];
      } else {
        // 没有可用的场次时间
        timeSlotData = [{
          id: bestRule.Id,
          startTime: '全天可用',
          endTime: '',
          available: true,
          productId: bestRule.ProductId,
          productSpecId: bestRule.Id,
          ruleName: bestRule.Name || '' // 保存规则名称
        }];
      }
      // 5. 检查是否有可购买的场次
      const hasAvailableSlots = timeSlotData.some(slot => slot.available);
      // 6. 如果没有任何场次或所有场次都不可购买，添加一个提示性的场次
      if (!timeSlotData.length) {
        item.timeSlots = [{
          id: null,
          startTime: '暂无可用场次',
          endTime: '',
          available: false,
          productSpecId: null
        }];

        // 提示用户
        uni.showToast({
          title: isToday ? '今日已无可用场次' : '所选日期无可用场次',
          icon: 'none',
          duration: 2000
        });
      } else {
        // 7. 更新场次列表 - 所有场次都显示，包括不可购买的
        item.timeSlots = timeSlotData;

        // 如果有可购买的场次，但没有可购买的场次被选中，选择第一个可购买的场次
        if (hasAvailableSlots && !item.timeSlots[item.selectedTimeSlot]?.available) {
          const firstAvailableIndex = item.timeSlots.findIndex(slot => slot.available);
          if (firstAvailableIndex !== -1) {
            item.selectedTimeSlot = firstAvailableIndex;
          }
        }
      }
    },

    // 格式化入住日期
    checkInDate(startDate) {
      return this.formatDateObject(startDate);
    },
    // 格式化离店日期
    checkOutDate(endDate) {
      return this.formatDateObject(endDate);
    },
    // 计算住宿天数
    nightsCount(dateRange) {
      if (!dateRange || dateRange.length !== 2) return 1;
      const start = new Date(dateRange[0]);
      const end = new Date(dateRange[1]);
      const diff = Math.abs(end - start);
      return Math.ceil(diff / (1000 * 60 * 60 * 24));
    },

    // 获取格式化的日期字符串 YYYY-MM-DD
    getFormattedDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    },

    // 获取明天的日期对象
    getTomorrowDate() {
      const date = new Date();
      date.setDate(date.getDate() + 1);
      return date;
    },

    // 获取指定天数后的日期对象
    getDateAfterDays(days) {
      const date = new Date();
      date.setDate(date.getDate() + days);
      return date;
    },

    // 格式化日期对象
    formatDateObject(dateStr) {
      if (!dateStr) return '';
      const date = new Date(dateStr);
      const month = date.getMonth() + 1;
      const day = date.getDate();
      const weekDay = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'][date.getDay()];
      return {month, day, weekDay};
    },

    // 格式化门票日期
    formatTicketDate(item) {
      if (!item.ticketDate) return '';
      const {month, day, weekDay} = this.formatDateObject(item.ticketDate);
      return `${month}月${day}日 ${weekDay}`;
    },

    onTicketDateChange(value, item) {
      item.ticketDate = value;
      item.selectedTimeSlot = 0;
      this.generateTimeSlots(item);
    },
    selectTimeSlot(item, slot, slotIndex) {
      // 检查场次是否可用
      if (!slot.available) {
        uni.showToast({
          title: '该场次剩余时间不足1小时',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      item.selectedTimeSlot = slotIndex;
    },
    onDateChange(value, item, ref) {
      if (!value || value.length !== 2) return;
      // 检查是否选择了过去的日期
      const today = new Date();
      today.setHours(0, 0, 0, 0); // 将时间设置为当天的开始
      const startDate = new Date(value[0]);
      const endDate = new Date(value[1])
      const nextDay = new Date(startDate);
      nextDay.setDate(nextDay.getDate() + 1);
      const nextDayFormatted = this.getFormattedDate(nextDay);

      const updateDateRange = (newRange) => {
        this.$refs[ref][0].clear();
        this.$nextTick(() => {
          item.dateRange = newRange;
        });
      };

      // 如果选择了过去的日期，重置为今天
      if (startDate < today) {
        const todayFormatted = this.getFormattedDate(today);
        // 计算明天日期
        const tomorrowDate = new Date(today);
        tomorrowDate.setDate(today.getDate() + 1);
        const tomorrowFormatted = this.getFormattedDate(tomorrowDate);
        // 更新日期范围并提示用户
        updateDateRange([todayFormatted, tomorrowFormatted]);
        uni.showToast({
          title: '不能选择过去的日期',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      // 检查开始日期和结束日期是否相同
      if (value[0] === value[1]) {
        // 更新日期范围
        updateDateRange([value[0], nextDayFormatted]);
        // 提示用户
        uni.showToast({
          title: '入住和离店日期不能相同',
          icon: 'none',
          duration: 2000
        });
        return;
      }
      // 检查日期是否超过一天
      const diff = Math.abs(endDate - startDate);
      if (Math.ceil(diff / (1000 * 60 * 60 * 24)) > 1) {
        // 更新日期范围
        updateDateRange([value[0], nextDayFormatted]);
        // 提示用户
        uni.showToast({
          title: '入住时间不能超过一天',
          icon: 'none',
          duration: 2000
        });
        return;
      }

      // 日期合法，更新dateRange
      this.dateRange = value;
    },

    // 用户选择相关方法
    openUserSelector(ref) {
      this.$refs[ref].open();
      // 打开时主动刷新一次数据
      setTimeout(() => {
        if (this.$refs[ref].$vm) {
          this.$refs[ref].$vm.init();
        }
      }, 300);
    },
    removeCommonGuest(guestIndex) {
      this.commonGuests.splice(guestIndex, 1);
    },
    closeUserSelector(ref) {
      this.$refs[ref].close();
    },
    onClearSelection() {
      this.commonGuests = [];
    },
    onSelectComplete(ref) {
      this.closeUserSelector(ref);
    },
    onUserSelected(userData) {
      this.commonGuests.push(userData);
    },

    // 打开地址选择器
    openAddressSelector(ref) {
      this.$refs[ref][0].open();
      // 打开时主动刷新一次数据
      setTimeout(() => {
        if (this.$refs[ref][0].$vm) {
          this.$refs[ref][0].$vm.init();
        }
      }, 300);
    },
    // 关闭地址选择器
    closeAddressSelector(ref) {
      this.$refs[ref][0].close();
    },
    // 地址选择完成
    onAddressSelected(address, item) {
      item.selectedAddress = address;
    },
    // 地址选择完成关闭弹窗
    onAddressSelectComplete(ref) {
      this.closeAddressSelector(ref);
    },
    currentSelectedAddress(item) {
      return item.selectedAddress; 
    },
    async getDefaultAddress(lastItemType2Index) {
      try {
        const {Data} = await getAcceptAddressList({
          Index: 1,
          Size: 100,
        });
        if (Data && Data.length) {
          // 查找默认地址，IsDefault值为1的地址
          const defaultAddress = Data.find(item => item.IsDefault === 1);
          if (defaultAddress) {
            // 设置为已选中的地址
            this.packageInfo.packageItems[lastItemType2Index].selectedAddress = {
              id: defaultAddress.Id,
              name: defaultAddress.Name,
              phone: defaultAddress.Mobile || '',
              province: defaultAddress.Province,
              city: defaultAddress.City,
              county: defaultAddress.County,
              address: defaultAddress.Address,
              isDefault: true
            };
          }
        }
      } catch (error) {
        console.error('获取默认地址失败:', error);
      }
    },

    // 获取用户优惠券
    async getCoupon() {
      try {
        const { Data } = await GetUserCoupons({
          Index: 1,
          Size: 100,
          BusinessId: this.packageInfo.businessId,
          CouponStatus: 1
        });

        if (!Data || !Array.isArray(Data)) {
          this.hasCoupons = false;
          return;
        }

        const currentDate = Date.now();

        // 筛选有效优惠券
        const validCoupons = Data.filter(coupon => {
          const startTime = Date.parse(coupon.EffectStartDatetime);
          const endTime = Date.parse(coupon.EffectEndDatetime);
          return currentDate < endTime && currentDate > startTime;
        });

        // 设置是否有可用优惠券
        this.hasCoupons = validCoupons.length > 0;

      } catch (error) {
        this.hasCoupons = false;
      }
    },

    // 跳转到优惠券选择页面
    navigateToCoupons() {
      // 准备传递的参数
      const params = {
        businessId: this.packageInfo.businessId,
        totalPrice: this.totalPrice,
        productId: this.packageInfo.productId,
        selectedCoupons: this.useCoupons || []
      };

      // 跳转到优惠券页面
      uni.navigateTo({
        url: '/mall_subpages/goods/coupons?params=' + encodeURIComponent(JSON.stringify(params))
      });
    },

    // 从优惠券页面返回时接收数据
    onCouponSelected(coupons) {
      this.lastTotalPrice = this.totalPrice;
      this.useCoupons = coupons || [];

      // 计算优惠券总折扣金额
      this.calculateCouponDiscount();
    },

    // 计算优惠券总折扣金额
    calculateCouponDiscount() {
      if (!this.useCoupons || this.useCoupons.length === 0) {
        this.couponTotalDiscount = 0;
        return;
      }

      let totalDiscount = 0;
      const originalPrice = parseFloat(this.totalPrice);

      this.useCoupons.forEach(coupon => {
        if (coupon.CouponTemple && coupon.CouponTemple.FullReduceAmount) {
          totalDiscount += parseFloat(coupon.CouponTemple.FullReduceAmount);
        }
      });

      // 确保折扣不超过总价
      this.couponTotalDiscount = Math.min(totalDiscount, originalPrice);
    },

    // 构建优惠券参数
    buildCouponParams() {
      if (!this.useCoupons || this.useCoupons.length === 0) {
        return [];
      }

      return this.useCoupons.map(coupon => ({
        CouponCode: coupon.CouponCode,
        BusinessId: coupon.BusinessIds ? this.packageInfo.businessId : 0
      }));
    },

    // 获取积分比例
    async getPointsRatio() {
      try {
        const res = await getPointsExchangeRatio();
        const data = res.Data;
        this.pointsRatio = data.PointToCNYRatio;
      } catch (error) {
        this.pointsRatio = 1;
      }
    },

    validateOrderData() {
      let validateFlag = true;
      let errorTips = '';
      for (let i = 0; i < this.packageInfo.packageItems.length; i++) {
        const item = this.packageInfo.packageItems[i];
        const includesFlag = [2, 11, 13, 18, 19].includes(item.type);
        if (!includesFlag) continue;
        if (item.hasAddress && !item.selectedAddress) {
          validateFlag = false;
          errorTips = '请选择收货地址';
          break;
        }
        // if (item.hasRzDate && !item.dateRange.length) {
        //   validateFlag = false;
        //   errorTips = '请选择入住时间';
        //   break;
        // }
        // if ([11, 18].includes(item.type) && item.hasTicket && !item.ticketDate) {
        //   validateFlag = false;
        //   errorTips = '请选择使用日期';
        //   break;
        // }
        // if (item.hasTimeSlots && item.timeSlots.length && (!item.selectedTimeSlot && item.selectedTimeSlot !== 0)) {
        //   validateFlag = false;
        //   errorTips = '请选择场次';
        //   break;
        // }
      }

      if (validateFlag && this.requiresCommonGuestInfo && this.commonGuests.length === 0) {
        validateFlag = false;
        errorTips = `请选择${this.commonGuestInfoTitle.replace('信息', '')}`;
      }
      if (!validateFlag) {
        uni.showToast({
          title: errorTips,
          icon: 'none'
        });
        return false;
      }
      return true;
    },

    // 提交订单
    async submitOrder() {
      // 防重复提交
      if (this.isSubmitting) {
        uni.showToast({
          title: '订单正在提交中，请稍候',
          icon: 'none'
        });
        return;
      }

      if (!this.checked) {
        uni.showToast({
          icon: "none",
          title: "请先勾选同意协议",
        });
        return;
      }

      // 验证订单数据
      if (!this.validateOrderData()) {
        return;
      }

      // 设置提交状态
      this.isSubmitting = true;

      // 显示加载提示
      uni.showLoading({
        title: this.$t('order.submitting'),
        mask: true
      });
      try {
        // 构建订单参数
        const params = {
          ProductId: this.packageInfo.productId,
          PackProductId: this.packageInfo.productId,
          ProductName: this.packageInfo.name,
          ProductType: 17, // 套餐类型
          Price: this.packageInfo.price,
          PayStatus: 0,
          Point: 0,
          Count: 1, // 套餐数量默认为1
          Deposit: 0,
          ContactMobile: '',
          ContactName: '',
          CouponDiscount: this.couponTotalDiscount,
          OriginalPrice: this.packageInfo.price,
          PlatformType: 20, // 小程序
          SettleType: 1,
          payType: 0,
          IsTicket: 1, // 电子票
          OrderRemak: this.remark || '',
          BusinessId: this.packageInfo.businessId || 0,
          // 添加productMenuList.vue中使用的字段
          SelfOrLogs: '',
          RoomCount: 0,
          LocalBusinessId: '',
          // 使用当前日期作为默认订单开始日期
          OrderStartDate: this.getFormattedDate(new Date()),
          OrderEndDate: '',
          ContactPerson: [],
          ContactPhone: [],
          IDCards: [],
          Persons: [],
          // 套餐特有参数
          PackProductItems: this.packageInfo.packageItems.map(item => {
            if (item.timeSlots && (item.selectedTimeSlot || item.selectedTimeSlot === 0)) {
              item.slotTime = `${item.timeSlots[item.selectedTimeSlot].startTime}-${item.timeSlots[item.selectedTimeSlot].endTime}`
            }
            const resItems = {
              ProductId: item.productId,
              ProductName: item.name,
              ProductType: item.type,
              Price: item.price,
              Count: 1,
              ProductSpecId: item.productSpecId,
              DateRange: item.dateRange,
              Guests: item.hasRzrInfo ? this.commonGuests : [],
              SelectedAddress: item.selectedAddress,
              TicketDate: item.ticketDate,
              SlotTime: item.slotTime
            }
            return resItems
          })
        };

        // 构建优惠券参数
        const useCoupons = this.isPointsPayment ? [] : this.buildCouponParams();
        let ReceiptInformation 
        const type2List = this.packageInfo.packageItems.filter(item => item.type === 2);
        if (type2List.length) {
          const { selectedAddress } = type2List.at(-1);
          ReceiptInformation = {
            Province: selectedAddress.province,
            City: selectedAddress.city,
            County: selectedAddress.county,
            Address: selectedAddress.address,
            Name: selectedAddress.name,
            Mobile: selectedAddress.phone
          }
        }

        // 组装最终请求参数
        const requestParams = {
          PackOrders: [params],
          Coupons: useCoupons,
          ReceiptInformation
        };
        const packItemOrder = this.packageInfo.packageItems.map(item => {
          const res = {
            BusinessId: item.businessId,
            ProductId: item.productId,
            ProductName: item.name,
            ProductType: item.type,
            Price: item.price,
            Count: 1
          }
          if (item.hasRzrInfo) {
            const persons = this.commonGuests.map(guest => ({
              Name: guest.name,
              IDCard: guest.idCard,
              Mobile: guest.phone
            }));
            res.Persons = persons;

            // if (item.type === 13) {
            //   res.OrderStartDate = item.dateRange[0];
            //   res.OrderEndDate = item.dateRange[1];
            //   item.RoomCount = 1;
            // } else if ([11, 18].includes(item.type)) {
            //   res.OrderStartDate = item.ticketDate;
            //   res.ProductSpecId = item.timeSlots[item.selectedTimeSlot].id;
            // } else
			 
			 if (item.type === 19) {
              let orderRemak = ``;
              this.commonGuests.forEach(guest => {
                orderRemak += `乘坐人：${guest.name}`;
                orderRemak += `，身份证：${guest.idCard}`;
                orderRemak += `，联系电话：${guest.phone}；`;
              });
              res.OrderRemak = orderRemak;
            }
          }
          return res
        })
        requestParams.PackOrders[0].PackItemOrder = packItemOrder

        // 如果是积分支付类型，添加UsePoints参数
        if (this.isPointsPayment) {
          requestParams.UsePoints = true;
        }
        // 调用套餐订单接口
        // const { Data } = await addPackProductOrders(requestParams);
        const { Data } = await AddOrders_V2(requestParams)

        // 隐藏加载提示
        uni.hideLoading();

        if (!Data || !Data.OrdersOnLineId) {
          uni.showToast({
            title: this.$t('order.submitFailed'),
            icon: 'none',
            duration: 2000
          });
          return;
        }

        if (this.isPointsPayment) {
          uni.redirectTo({
            url: `/mall_subpages/goods/success?id=${Data.OrdersOnLineId}&delta=1`
          });
        } else {
          // 跳转到支付页面
          // uni.redirectTo({
          //   url: `/mall_subpages/goods/payment?id=${Data.OrdersOnLineId}&delta=2`
          // });
		  console.log("Data =>",Data);
		  // console.log("JSON_Data",JSON.parse(Data.WxJsApiParam));
		  if(Data && Data.WxJsApiParam){
			  const param = JSON.parse(Data.WxJsApiParam)
			  this.wxPay(param)
		  }else{
			  uni.showToast({
			    title: error.Msg || this.$t('order.submitFailed'),
			    icon: 'none',
			    duration: 2000
			  })
		  }
        }
      } catch (error) {
        uni.hideLoading();
        uni.showToast({
          title: error.Msg || this.$t('order.submitFailed'),
          icon: 'none',
          duration: 2000
        });
      } finally {
        // 延迟重置提交状态，防止快速重复点击
        setTimeout(() => {
          this.isSubmitting = false;
        }, 2000);
      }
    },
	
	wxPay(paymentParams){
		// 调用微信支付
		uni.requestPayment({
		  provider: 'wxpay',
		  timeStamp: paymentParams.timeStamp,
		  nonceStr: paymentParams.nonceStr,
		  package: paymentParams.package,
		  signType: paymentParams.signType,
		  paySign: paymentParams.paySign,
		  success: () => {
		    uni.switchTab({
		      url: '/pages/order/index',
		      success: () => {
		        this.$store.commit('setCurrent', 3);
		      }
		    })
		  },
		  fail: (err) => {
		    this.isLoading = false;
		    uni.hideLoading();
		    console.log('支付失败:', JSON.stringify(err));
		    uni.showToast({
		      title: this.$t('payment.cancelled'),
		      icon: 'none',
		      duration: 2000
		    });
		  }
		});
	},

    // 获取格式化的日期字符串 YYYY-MM-DD
    getFormattedDate(date) {
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0');
      const day = String(date.getDate()).padStart(2, '0');
      return `${year}-${month}-${day}`;
    }
  }
}
</script>

<template>
  <view class="package-container">

    <!-- 套餐基本信息 -->
    <view class="package-info">
      <view class="package-image">
        <image :src="packageInfo.image" mode="aspectFill"></image>
      </view>
      <view class="package-details">
        <view class="package-name">{{packageInfo.name}}</view>
        <view class="price" v-if="!isPointsPayment">¥{{packageInfo.price}}</view>
        <view class="price points-price" v-else>{{Math.round(packageInfo.price * pointsRatio)}} {{ $t('common.points') }}</view>
      </view>
    </view>

    <!-- 套餐子项目信息 -->
    <view v-if="packageInfo.packageItems && packageInfo.packageItems.length" class="package-items">
      <view class="section-title">套餐包含项目</view>

      <!-- 遍历套餐项目 -->
      <view
        class="package-item-card"
        v-for="(item, index) in packageInfo.packageItems"
        :key="index"
      >
        <!-- 项目标题 -->
        <view class="item-header">
          <view class="item-type-badge" :class="'type-' + item.type">
            <text v-if="item.type === 11">{{ $t('package.ticketType') }}</text>
            <text v-else-if="item.type === 13">{{ $t('package.hotelType') }}</text>
            <text v-else>{{ $t('package.productType') }}</text>
          </view>
          <view class="item-title">{{item.name}}</view>
        </view>

        <!-- 项目图片和信息 -->
        <view class="item-content">
          <view class="item-image">
            <image :src="item.image" mode="aspectFill"></image>
          </view>
          <view class="item-info">
            <view class="item-price-row">
              <text class="item-price">¥{{item.showPrice}}</text>
              <view class="quantity-info">
                <text class="quantity-text">{{ $t('package.quantity', {count: 1}) }}</text>
              </view>
            </view>
          </view>
        </view>

        <!-- 地址选择弹窗 -->
        <uni-popup v-if="item.type === 2" :ref="`shopRef_${index}`" type="bottom">
          <view class="popup-content">
            <view class="popup-header">
              <text class="popup-title">选择收货地址</text>
              <text class="popup-close" @click="closeAddressSelector(`shopRef_${index}`)">×</text>
            </view>
            <view class="popup-body">
              <select-address
                :selectedAddress="currentSelectedAddress(item)"
                @select="onAddressSelected($event, item)"
                @complete="onAddressSelectComplete(`shopRef_${index}`)"
              />
            </view>
          </view>
        </uni-popup>



        <!-- 收货地址 -->
        <view v-if="item.hasAddress" class="item-content">
          <view class="address-info">
            <view class="info-header">
              <view class="info-title">收货地址</view>
            </view>
            <!-- 已选择的地址 -->
            <view
              v-if="item.selectedAddress"
              class="selected-address"
              @click="openAddressSelector(`shopRef_${index}`)"
            >
              <view class="address-content">
                <view class="address-header">
                  <text class="address-name">{{ item.selectedAddress.name }}</text>
                  <text class="address-phone">{{ item.selectedAddress.phone }}</text>
                </view>
                <view class="address-detail">
                  {{ item.selectedAddress.province }} {{ item.selectedAddress.city }} {{ item.selectedAddress.county }}
                  {{ item.selectedAddress.address }}
                </view>
              </view>
              <view class="address-arrow">
                <uni-icons type="forward" size="16" color="#BBBBBB"></uni-icons>
              </view>
            </view>
            <!-- 未选择地址时的提示 -->
            <view
              v-else
              class="no-address"
              @click="openAddressSelector(`shopRef_${index}`)"
            >
              <text class="no-address-tip">请选择收货地址</text>
              <view class="address-arrow">
                <uni-icons type="forward" size="16" color="#BBBBBB"></uni-icons>
              </view>
            </view>
          </view>
        </view>

        <!-- 入住时间 -->
        <view v-if="item.hasRzDate" class="item-content">
          <view class="booking-info">
            <uni-datetime-picker
              v-model="item.dateRange"
              :ref="`hotelRoomRef_${index}`"
              type="range"
              :clear-icon="false"
              :start="today"
              :end="endLimit"
              @change="onDateChange($event, item, `hotelRoomRef_${index}`)"
            >
              <view class="date-range-display">
                <view class="date-section">
                  <view class="date-label">今天入住</view>
                  <view class="date-content">
                    <text class="date-month">{{ checkInDate(item.dateRange[0]).month }}月</text>
                    <text class="date-day">{{ checkInDate(item.dateRange[0]).day }}日</text>
                    <text class="date-week">{{ checkInDate(item.dateRange[0]).weekDay }}</text>
                  </view>
                </view>
                <view class="date-section">
                  <view class="date-label">明天离店</view>
                  <view class="date-content">
                    <text class="date-month">{{ checkOutDate(item.dateRange[1]).month }}月</text>
                    <text class="date-day">{{ checkOutDate(item.dateRange[1]).day }}日</text>
                    <text class="date-week">{{ checkOutDate(item.dateRange[1]).weekDay }}</text>
                  </view>
                </view>
                <view class="nights-count">
                  <view class="night-badge">共{{ nightsCount(item.dateRange) }}晚
                    <image src="/static/home/right-arrow-black.png"></image>
                  </view>
                </view>
              </view>
            </uni-datetime-picker>
          </view>
        </view>

        <!-- 门票日期和场次选择 -->
   <!--     <view v-if="[11, 18].includes(item.type)" class="item-content">
          <view class="ticket-booking-info">
            <view class="info-title">使用日期</view>
            <view class="date-picker-area">
              <uni-datetime-picker
                v-model="item.ticketDate"
                type="date"
                :clear-icon="false"
                :start="today"
                :end="endLimit"
                @change="onTicketDateChange($event, item)"
              >
                <view class="ticket-date-display">
                  <view class="selected-date">
                    <text>{{ formatTicketDate(item) }}</text>
                    <uni-icons type="arrowright" size="16" color="#999"></uni-icons>
                  </view>
                </view>
              </uni-datetime-picker>
            </view>

            <view v-if="item.hasTimeSlots && item.timeSlots.length" class="time-slot-section">
              <view class="title-row">
                <view class="info-title">选择场次</view>
                <view class="time-tip">仅可选择剩余时间大于1小时的场次</view>
              </view>
              <view class="time-slot-list">
                <view
                    v-for="(slot, slotIndex) in item.timeSlots"
                    :key="slotIndex"
                    class="time-slot-item"
                    :class="{
                    'selected-slot': item.selectedTimeSlot === slotIndex,
                    'disabled-slot': !slot.available
                  }"
                    @click="selectTimeSlot(item, slot, slotIndex)"
                >
                  <text>{{ slot.startTime }}{{ slot.endTime ? ' - ' + slot.endTime : '' }}</text>
                </view>
              </view>
            </view>
          </view>
        </view> -->

      </view>
    </view>

    <!-- 通用游客/入住人信息 -->
    <view v-if="requiresCommonGuestInfo" class="guest-info-wrapper">
      <view class="guest-info">
        <view class="info-header">
          <view class="info-title">{{ commonGuestInfoTitle }}</view>
          <view class="add-guest-btn" @click="openUserSelector('commonUserRef')">
            <text class="add-icon">+</text>
            <text class="add-text">添加{{ commonGuestInfoTitle.replace('信息', '') }}</text>
          </view>
        </view>
        <!-- 游客列表 -->
        <view class="guest-list">
          <view class="guest-item" v-for="(guest, guestIndex) in commonGuests" :key="guestIndex">
            <view class="guest-index">{{ commonGuestInfoTitle.replace('信息', '').split('/')[0] }}{{ guestIndex + 1 }}</view>
            <view class="guest-details">
              <text class="guest-name">{{ guest.name }}</text>
              <text class="id-number">- {{ guest.phone }}</text>
              <text class="id-full">{{ guest.idCard }}</text>
            </view>
            <view class="delete-btn" @click="removeCommonGuest(guestIndex)">
              <text class="delete-icon">×</text>
            </view>
          </view>
          <!-- 没有游客时的提示 -->
          <view class="no-guest" v-if="commonGuests.length === 0">
            <text class="no-guest-tip">请添加{{ commonGuestInfoTitle.replace('信息', '') }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 通用用户选择弹窗 -->
    <uni-popup v-if="requiresCommonGuestInfo" ref="commonUserRef" type="bottom">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">选择{{ commonGuestInfoTitle.replace('信息', '') }}</text>
          <text class="popup-close" @click="closeUserSelector('commonUserRef')">×</text>
        </view>
        <view class="popup-body">
          <select-user
            :selectedGuests="commonGuests"
            @select="onUserSelected"
            @clear="onClearSelection"
            @complete="onSelectComplete('commonUserRef')"
          />
        </view>
      </view>
    </uni-popup>

    <!-- 备注 -->
    <view class="remarks">
      <view class="section-title">{{ $t('order.remarks') }}</view>
      <view class="input-wrapper">
        <input class="remark-input" type="text" v-model="remark" :placeholder="$t('order.remarks')" placeholder-style="color: #999;"/>
      </view>
    </view>

    <!-- 优惠券区域 - 非积分模式才显示 -->
    <view class="coupon-area" v-if="!isPointsPayment">
      <view class="coupon-section">
        <view class="coupon-header">
          <view class="section-title">{{ $t('order.coupon.title') }}</view>
          <view class="coupon-status" v-if="useCoupons.length > 0">
            {{ $t('order.coupon.selected', {count: useCoupons.length, amount: couponTotalDiscount.toFixed(2)}) }}
          </view>
          <view class="coupon-status available" v-else-if="hasCoupons">
            {{ $t('order.coupon.available') }}
          </view>
          <view class="coupon-status unavailable" v-else>
            {{ $t('order.coupon.unavailable') }}
          </view>
        </view>
        <view class="coupon-selection" @click="navigateToCoupons">
          <view class="select-text">{{ $t('order.coupon.select') }}</view>
          <uni-icons type="forward" size="16" color="#BBBBBB"></uni-icons>
        </view>
      </view>
    </view>

    <!-- 预定须知 -->
    <view class="booking-notice">
      <view class="section-title">{{ $t('order.bookingNotice') }}</view>
      <view class="notice-content">
        <mp-html :content="packageInfo.bookingNotice" />
      </view>
    </view>

    <hz-safe-area></hz-safe-area>

    <!-- 同意条款区域 -->
		<view class="agreement-row">
			<view class="agreement-icon" @click="changeCheked">
				<uni-icons
					v-if="checked"
					type="circle-filled"
					color="#1AAC19"
					size="26"
					class="agreementIcon"
				/>
				<uni-icons
					v-else
					type="circle"
					color="#1AAC19"
					size="26"
					class="agreementIcon"
				/>
			</view>
			<view class="agreement-container">
				<text>我已阅读协议</text>、
				<text class="blueText" @click.stop="goToTermsDetail(5773)">《用户协议》</text>丶
				<text class="blueText" @click.stop="goToTermsDetail(5774)">《隐私政策》</text>丶
				<text class="blueText" @click.stop="goToTermsDetail(5775)">《免责声明》</text>
			</view>
		</view>

    <!-- 底部结算栏 -->
    <view class="bottom-bar">
      <view class="bottom-bar_inner">
        <view class="price-section">
          <text class="price-label" v-if="!isPointsPayment">{{ $t('order.orderAmount') }} ¥</text>
          <text class="price-label" v-else>{{ $t('order.orderPoints') }} </text>
          <template v-if="!isPointsPayment">
            <u-count-to
              class="total-price"
              ref="countTo"
              :start-val="Number(lastTotalPrice)"
              :end-val="Number(totalPrice)"
              :duration="1000"
              :decimals="2"
              :autoplay="true"
              :color="'#FF4B31'"
              :bold="true"
              :fontSize="28"
            ></u-count-to>
          </template>
          <template v-else>
            <text class="total-price points">{{totalPoints}}</text>
          </template>
        </view>
        <view class="submit-btn" @click="submitOrder">
          <text>去支付</text>
        </view>
      </view>
      <hz-safe-area></hz-safe-area>
    </view>
  </view>
</template>

<style scoped lang="scss">
.package-container {
  padding: 30rpx 30rpx 226rpx;
  background-color: #F5F5F5;
  min-height: 100vh;
}

.booking-info,
.guest-info,
.address-info,
.ticket-booking-info {
  width: 100%;
  background-color: #FFF;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

// 日期选择
.date-range-display {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: 20rpx 0;
}

.date-section {
  flex: 1;
  .date-label {
    font-size: 24rpx;
    color: #666;
    margin-bottom: 10rpx;
  }
  .date-content {
    display: flex;
    align-items: baseline;
    .date-day, .date-month {
      font-size: 28rpx;
      color: #333;
      font-weight: bold;
    }
    .date-month {
      margin-left: 8rpx;
    }
    .date-week {
      font-size: 28rpx;
      color: #666;
      margin-left: 16rpx;
    }
  }
}
.nights-count {
  padding-left: 20rpx;
  .night-badge {
    font-size: 24rpx;
    color: #666;
    image {
      height: 24rpx;
      width: 13rpx;
      margin-left: 10rpx;
    }
  }
}

.date-picker-area {
  margin-bottom: 30rpx;
}
.ticket-date-display {
  display: flex;
  align-items: center;
  background-color: #F5F5F5;
  padding: 20rpx;
  border-radius: 8rpx;
}
.selected-date {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  font-size: 28rpx;
  color: #333;
}
.time-slot-section {
  margin-top: 20rpx;
}
.title-row {
  display: flex;
  align-items: baseline;
  justify-content: space-between;
  margin-bottom: 20rpx;
}
.time-tip {
  font-size: 24rpx;
  color: #999;
}
.time-slot-list {
  display: flex;
  flex-wrap: wrap;
  margin-top: 20rpx;
}

.time-slot-item {
  width: 48%;
  height: 80rpx;
  line-height: 80rpx;
  text-align: center;
  background-color: #F5F5F5;
  border-radius: 8rpx;
  margin-bottom: 20rpx;
  color: #333;
  font-size: 28rpx;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  padding: 0 10rpx;
  box-sizing: border-box;
  position: relative;

  &:nth-child(odd) {
    margin-right: 4%;
  }

  &.selected-slot {
    background-color: #498FFF;
    color: #FFF;
  }

  &.disabled-slot {
    background-color: #f5f5f5;
    color: #aaaaaa;
    border: 1px dashed #dddddd;
  }
}

.guest-info {
  .info-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 20rpx;
    .add-guest-btn {
      display: flex;
      align-items: center;
      background-color: #f8f8f8;
      padding: 6rpx 16rpx;
      border-radius: 30rpx;
      .add-icon {
        font-size: 28rpx;
        color: #498FFF;
        margin-right: 6rpx;
      }
      .add-text {
        color: #498FFF;
        font-size: 24rpx;
      }
    }
  }
  .guest-list {
    .guest-item {
      display: flex;
      align-items: center;
      padding: 20rpx 0;
      border-bottom: 1rpx solid #eee;
      &:last-child {
        border-bottom: none;
      }
      .guest-index {
        font-size: 28rpx;
        color: #666;
        margin-right: 20rpx;
        min-width: 80rpx;
      }
      .guest-details {
        flex: 1;
        .guest-name {
          font-size: 28rpx;
          color: #333;
        }
        .id-number {
          font-size: 28rpx;
          color: #666;
          margin-left: 10rpx;
        }
        .id-full {
          display: block;
          font-size: 24rpx;
          color: #999;
          margin-top: 6rpx;
        }
      }
      .delete-btn {
        width: 60rpx;
        height: 60rpx;
        display: flex;
        align-items: center;
        justify-content: center;
        .delete-icon {
          font-size: 36rpx;
          color: #ccc;
        }
      }
    }
    .no-guest {
      padding: 40rpx 0;
      text-align: center;
      .no-guest-tip {
        font-size: 28rpx;
        color: #999;
      }
    }
  }
}

// 收货地址样式
.address-info {
  background-color: #FFF;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
  .info-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;
  }

  .selected-address {
    display: flex;
    align-items: center;
    background-color: #F5F5F5;
    border-radius: 8rpx;
    padding: 20rpx;

    .address-content {
      flex: 1;

      .address-header {
        display: flex;
        align-items: center;
        margin-bottom: 10rpx;

        .address-name {
          font-size: 28rpx;
          color: #333;
          font-weight: 500;
          margin-right: 20rpx;
        }

        .address-phone {
          font-size: 26rpx;
          color: #666;
        }
      }

      .address-detail {
        font-size: 26rpx;
        color: #666;
        line-height: 1.4;
      }
    }

    .address-arrow {
      margin-left: 10rpx;
    }
  }

  .no-address {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background-color: #F5F5F5;
    border-radius: 8rpx;
    padding: 30rpx 20rpx;

    .no-address-tip {
      font-size: 28rpx;
      color: #666;
    }
  }
}

// 卡片组件
.package-info, .package-items, .remarks, .booking-notice, .coupon-area {
  background-color: #FFF;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

// 套餐基本信息
.package-info {
  display: flex;
  align-items: center;

  .package-image {
    width: 160rpx;
    height: 160rpx;
    border-radius: 8rpx;
    overflow: hidden;
    margin-right: 20rpx;

    image {
      width: 100%;
      height: 100%;
    }
  }

  .package-details {
    flex: 1;

    .package-name {
      font-size: 32rpx;
      font-weight: 600;
      color: #333;
      margin-bottom: 10rpx;
      // white-space: nowrap;
      overflow: hidden;
      text-overflow: ellipsis;
	  
    }

    .price {
      font-size: 36rpx;
      color: #498FFF;
      font-weight: bold;
      margin-top: 10rpx;

      &.points-price {
        color: #FF4B31;
      }
    }
  }
}

// 套餐子项目
.package-items {
  .section-title {
    font-size: 30rpx;
    font-weight: 500;
    color: #333;
    margin-bottom: 20rpx;
  }

  .package-item-card {
    background-color: #FAFAFA;
    border-radius: 8rpx;
    padding: 20rpx;
    margin-bottom: 20rpx;

    .item-header {
      display: flex;
      align-items: center;
      margin-bottom: 15rpx;

      .item-type-badge {
        padding: 4rpx 12rpx;
        border-radius: 4rpx;
        font-size: 22rpx;
        margin-right: 10rpx;

        &.type-11 {
          background-color: #FFE4E1;
          color: #FF6347;
        }

        &.type-13 {
          background-color: #E6F7FF;
          color: #1890FF;
        }

        &.type-12 {
          background-color: #F0F5FF;
          color: #597EF7;
        }
      }

      .item-title {
        font-size: 28rpx;
        font-weight: 500;
        color: #333;
      }
    }

    .item-content {
      display: flex;
      margin-bottom: 15rpx;

      .item-image {
        width: 120rpx;
        height: 120rpx;
        border-radius: 6rpx;
        overflow: hidden;
        margin-right: 15rpx;

        image {
          width: 100%;
          height: 100%;
          object-fit: cover;
        }
      }

      .item-info {
        flex: 1;
        display: flex;
        flex-direction: column;
        justify-content: space-between;

        .item-price-row {
          display: flex;
          align-items: center;
          justify-content: space-between;

          .item-price {
            font-size: 30rpx;
            color: #FF4B31;
            font-weight: 500;
			  text-decoration: line-through;
          }
        }
      }
    }
  }
}

// 标题样式
.section-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
}

.section-subtitle {
  font-size: 26rpx;
  color: #666;
  margin-bottom: 10rpx;
}

// 输入框
.input-wrapper {
  background-color: #F5F5F5;
  border-radius: 8rpx;
  padding: 20rpx;

  .remark-input {
    width: 100%;
    font-size: 28rpx;
    color: #333;
  }
}

// 优惠券区域
.coupon-area {
  background-color: #FFF;
  border-radius: 12rpx;
  padding: 30rpx;
  margin-bottom: 20rpx;
}

.coupon-section {
  .coupon-header {
    display: flex;
    align-items: center;
    margin-bottom: 20rpx;

    .section-title {
      margin-bottom: 0;
      margin-right: 20rpx;
    }

    .coupon-status {
      flex: 1;
      font-size: 24rpx;
      color: #498FFF;

      &.available {
        color: #498FFF;
      }

      &.unavailable {
        color: #999;
      }
    }
  }

  .coupon-selection {
    display: flex;
    justify-content: space-between;
    align-items: center;
    height: 80rpx;
    padding: 0 20rpx;
    background-color: #F5F5F5;
    border-radius: 8rpx;

    .select-text {
      font-size: 28rpx;
      color: #666;
    }
  }
}

// 须知内容
.notice-text {
  font-size: 26rpx;
  color: #666;
  line-height: 1.6;
}

.agreement-row {
  position: fixed;
  left: 0;
  bottom: 166rpx;
  display: flex;
  align-items: flex-start;
  align-items: center;
  background-color: #fff;
  padding: 24rpx;
  z-index: 11;
  border-bottom: 2rpx solid #f0f0f0;
  .agreement-icon {
    width: 10%;
    margin-right: 16rpx;
  }
  .agreement-container {
    flex: 1;
    display: flex;
    flex-wrap: wrap;
    font-size: 28rpx;
  }
  .blueText {
    color: #2796ff;
  }
}

// 底部栏
.bottom-bar {
  position: fixed;
  bottom: 0;
  left: 0;
  right: 0;
  background-color: #FFF;
  box-shadow: 0 -2rpx 10rpx rgba(0, 0, 0, 0.05);
  z-index: 11;

  .bottom-bar_inner {
    display: flex;
    height: 100rpx;
    align-items: center;
    padding: 0 30rpx;
    width: 100%;
  }

  .price-section {
    flex: 1;
    display: flex;
    align-items: baseline;

    .price-label {
      font-size: 26rpx;
      color: #666;
    }

    .total-price {
      font-size: 40rpx;
      color: #498FFF;
      font-weight: bold;

      &.points {
        color: #FF4B31;
      }
    }
  }

  .submit-btn {
    background: linear-gradient(135deg, #498FFF 0%, #3A7FE6 100%);
    border-radius: 40rpx;
    height: 80rpx;
    padding: 0 50rpx;
    display: flex;
    align-items: center;
    justify-content: center;

    text {
      color: #FFF;
      font-size: 30rpx;
      font-weight: 500;
    }
  }
}

.quantity-info {
  font-size: 24rpx;
  color: #999;
  padding: 6rpx 12rpx;
  background-color: #f5f5f5;
  border-radius: 20rpx;

  .quantity-text {
    font-size: 24rpx;
    color: #666;
  }
}

// 弹窗样式
.popup-content {
  width: 100%;
  background-color: #FFF;
  border-radius: 12rpx;
  overflow: hidden;
  .popup-header {
    display: flex;
    justify-content: space-between;
    align-items: center;
    padding: 30rpx;
    border-bottom: 1rpx solid #eee;
    .popup-title {
      font-size: 32rpx;
      font-weight: 500;
      color: #333;
    }
    .popup-close {
      font-size: 40rpx;
      color: #999;
      line-height: 1;
    }
  }
  .popup-body {
    max-height: 800rpx;
    overflow-y: auto;
  }
}
// 通用标题
.info-title {
  font-size: 30rpx;
  font-weight: 500;
  color: #333;
  margin-bottom: 20rpx;
}
</style>
